package com.yh.servlet.admin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yh.dto.ZhanfengDTO;
import com.yh.service.UserService;
import com.yh.service.impl.UserServiceImpl;

//@WebServlet("/admin/user-add.let")
public class UserAddServlet extends HttpServlet{

	private Logger log = LoggerFactory.getLogger(UserAddServlet.class);
	private UserService userService = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");//设置请求的字符集编码，默认：iso-8859-1,本质设置的是请求正文的字符集编码.post的字符集编码
		//乱码问题：iso-8859-1 -> UTF-8
//		String oldStr = "";//有乱码问题的字符串
//		String newStr = new String(oldStr.getBytes("ISO-8859-1"),"UTF-8");
		
		//获取参数
		ZhanfengDTO user = new ZhanfengDTO();
		
		user.setZfName(req.getParameter("userName"));
		user.setZfPassword(req.getParameter("userPassword"));
		user.setZfSex(req.getParameter("userSex"));
		
		/**
		 * //参数获取的其它知识点
		//复选框的值，或多个input名字相同的值怎么获取？
		String userLoves = request.getParameter("userLoves");//只会获取第一个值
		System.out.println("userLoves="+userLoves);
		String[] userLovess = request.getParameterValues("userLoves");//获取参数值的数组
		System.out.println("userLoves="+Arrays.toString(userLovess));
		
		//请求头也是一种参数
		String accept = request.getHeader("Accept");
		System.out.println("Accept="+accept);
		Enumeration<String> headerNames = request.getHeaderNames();
		while(headerNames.hasMoreElements()){
			String name = headerNames.nextElement();
			System.out.println(name+"="+request.getHeader(name));
		}
		
		//请求对象提供的方法
		System.out.println("getRemoteAddr="+request.getRemoteAddr());
		System.out.println("getContextPath="+request.getContextPath());
//		System.out.println("getRealPath"+request.getRealPath("/"));
		System.out.println("getRealPath="+request.getServletContext().getRealPath("/"));
		
		user = new UserFormDTO();
		ServletUtil.fillBean(request, user, true);
		
		
		System.out.println(user);
		 */
		
//		System.out.println(user);
		log.debug("user:{}",user);
		
		try {
			userService.add(user);
			req.setAttribute("msg", "添加用户成功");
			req.setAttribute("href", "admin/user-list.let");
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("error", "添加用户失败:"+e.getMessage());
		}
		req.getRequestDispatcher("/admin/msg.jsp").forward(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
}
